package com.mvc.finance.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.business.model.PurchaseItem;
import com.mvc.business.service.OrderAssociatedManager;
import com.mvc.finance.model.BankStatementItem;
import com.mvc.framework.model.Auditable;
import com.mvc.framework.service.BaseService;

@Service
public class BankStatementItemManager extends BaseService<BankStatementItem, Integer> {

	@Autowired
	private OrderAssociatedManager	orderAssociatedManager;

	public List<BankStatementItem> getBankStatementItemsByBankStatementId(int bankStatementId) {
		BankStatementItem example = new BankStatementItem();
		example.setBankStatementId(bankStatementId);
		example.setRecStatus(Auditable.REC_STATUS_VALID);
		return getHibernateTemplate().findByExample(example);
	}

	public void deleteByBankStatementId(int bankStatementId) {
		deleteByWhere("bankStatementId = " + bankStatementId);
	}

	public void saveBankStatementItem(BankStatementItem orderItem, String operation) throws Exception {
		if (operation.equals("del")) {
			super.delete(orderItem.getId());
			orderAssociatedManager.saveBankStatementPurchases(orderItem.getBankStatementId());
		} else if (operation.equals("add")) {
			orderItem.setId(null);
			super.save(orderItem);
		} else if (operation.equals("edit")) {
			super.save(orderItem);
		}
	}

	public void updateBankStatementItemId(Integer oldOrderId, Integer newOrderId) {
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createQuery("update " + BankStatementItem.class.getName() + " set bankStatementId = " + newOrderId
		        + " where bankStatementId = " + oldOrderId);
		query.executeUpdate();
	}

	public Double getTotalQuantityOfPurchaseItem(Integer purchaseItemId) {
		String sql = "select sum(A.quantity) from " + BankStatementItem.class.getName()
		        + " A  where A.purchaseItemId=? AND A.recStatus=? AND bankStatementId > 0 ";
		return searchObjectBySql(Double.class, sql, new Object[] { purchaseItemId, Auditable.REC_STATUS_VALID });
	}

	public List<Integer> getPurchaseIds(Integer bankStatementId) {
		String sql = "select distinct (B.purchaseId) from " + BankStatementItem.class.getName() + " A, " + PurchaseItem.class.getName()
		        + " B where A.bankStatementId=? AND A.recStatus=? AND A.purchaseItemId = B.objectId AND B.recStatus = ? ";
		return searchBySql(Integer.class, sql, new Object[] { bankStatementId, Auditable.REC_STATUS_VALID, Auditable.REC_STATUS_VALID });
	}

}
